package com.atguigu.tingshu.payment.service.impl;

import com.atguigu.tingshu.model.payment.WeChatPayVo;
import com.atguigu.tingshu.payment.config.WxPayV3Config;
import com.atguigu.tingshu.payment.context.PaySubmitStrategyContext;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.atguigu.tingshu.payment.service.WxPayService;
import com.atguigu.tingshu.payment.strategy.PaySubmitStrategy;
import com.atguigu.tingshu.payment.util.PayUtil;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.QueryOrderByOutTradeNoRequest;
import com.wechat.pay.java.service.payments.model.Transaction;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class WxPayServiceImpl implements WxPayService {

	@Autowired
	private PaymentInfoService paymentInfoService;
	@Autowired
	private RSAAutoCertificateConfig autoCertificateConfig ;

	@Autowired
	private WxPayV3Config wxPayV3Config ;

	/**
	 * 关于该请求存在两种情况的请求：
	 * 1、订单支付的请求
	 * 2、充值支付的请求
	 */

	@Override
	public WeChatPayVo createJsapi(String paymentType, String orderNo) {

		// 使用微信支付平台的SDK请求Jsapi的下单接口，生成预交易订单
		PaySubmitStrategy paySubmitStrategy = PaySubmitStrategyContext.getPaySubmitStrategy(paymentType);
		WeChatPayVo weChatPayVo = paySubmitStrategy.paySubmit(paymentType, orderNo);
		return weChatPayVo;
	}

	@Override
	public boolean queryPayStatus(String orderNo) {

		try {

			// 通过微信支付的SDK查询支付结果
			JsapiServiceExtension service = new JsapiServiceExtension.Builder().config(autoCertificateConfig).build();
			QueryOrderByOutTradeNoRequest queryOrderByOutTradeNoRequest = new QueryOrderByOutTradeNoRequest() ;
			queryOrderByOutTradeNoRequest.setOutTradeNo(orderNo);
			queryOrderByOutTradeNoRequest.setMchid(wxPayV3Config.getMerchantId());
			Transaction transaction = service.queryOrderByOutTradeNo(queryOrderByOutTradeNoRequest);

			// 从transaction对象中获取交易的状态
			if(transaction != null && transaction.getTradeState() == Transaction.TradeStateEnum.SUCCESS) {		// 支付成功了

				// 把微信支付交易信息的状态改为已支付, 并且更改订单的状态，保存购买信息
				paymentInfoService.updatePaymentStatus(transaction) ;

				// 返回
				return true ;
			}

			// 返回
			return false;

		}catch (Exception e) {
			e.printStackTrace();
			return false ;
		}
	}

	@Override
	public void asyncNotify(HttpServletRequest request) {
		//从Request请求中获取请求参数，对参数进行解析

		// 从request请求头中构建RequestParam对象的参数
		String wechatSignature = request.getHeader("Wechatpay-Signature") ;
		String wechatpayNonce = request.getHeader("Wechatpay-Nonce") ;
		String wechatPaySerial = request.getHeader("Wechatpay-Serial") ;
		String wechatTimestamp = request.getHeader("Wechatpay-Timestamp") ;
		String requestBody = PayUtil.readData(request);

		//创建一个RequestParam对象
		RequestParam requestParam = new RequestParam.Builder()
				.serialNumber(wechatPaySerial)
				.nonce(wechatpayNonce)
				.signature(wechatSignature)
				.timestamp(wechatTimestamp)
				.body(requestBody).build();
		//创建通知解析器对象
		NotificationParser parser = new NotificationParser();
		Transaction transaction = parser.parse(requestParam, Transaction.class);

		// 从transaction对象中获取交易的状态
		if(transaction != null && transaction.getTradeState() == Transaction.TradeStateEnum.SUCCESS) {		// 支付成功了

			log.info("WxPayServiceImpl...asyncNotify...方法执行了，用户支付成功...");

			// 把微信支付交易信息的状态改为已支付, 并且更改订单的状态，保存购买信息
			paymentInfoService.updatePaymentStatus(transaction) ;

		}
	}
}
